package com.supreme.uploadserver.config;

import com.supreme.uploadserver.config.props.EmailSyncProps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import java.util.Properties;

@Slf4j
@Configuration
public class EmailSyncConfig {

    @Resource
    private EmailSyncProps emailSyncProps;

    @Bean
    public Store emailSyncStore() {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", emailSyncProps.getStoreProtocol());
        props.setProperty("mail.imap.host", emailSyncProps.getImapHost());
        props.setProperty("mail.imap.port", emailSyncProps.getImapPort());

        Session session = Session.getInstance(props);
        session.setDebug(emailSyncProps.getDebug());
        Store store = null;
        try {
            store = session.getStore(emailSyncProps.getStoreProtocol());
            store.connect(emailSyncProps.getUsername(), emailSyncProps.getPassword());
        } catch (MessagingException e) {
            log.error(e.getMessage());
        }

        return store;
    }

    @Bean
    public Folder emailSyncFolder(Store emailSyncStore) {
        Folder folder = null;
        try {
            folder = emailSyncStore.getFolder(emailSyncProps.getInbox());
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException e) {
            log.error(e.getMessage());
        }

        return folder;
    }

    @PreDestroy
    public void destroyEmailSyncStore() {
        System.out.println("@_@ destroyEmailSyncStore");
        try {
            emailSyncStore().close();
        } catch (MessagingException e) {
            log.error(e.getMessage());
        }
    }
}
